package concurrence;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by gzhd on 2017/11/21.
 */
public class CyclicBarrierDemo {
    public static class Soldier implements Runnable {
        private String soldier;
        private final CyclicBarrier cyclic;

        Soldier(CyclicBarrier cyclic, String soldierName) {
            this.cyclic = cyclic;
            this.soldier = soldierName;
        }

        @Override
        public void run() {
            try {
                System.out.println(soldier+"进入RUN队列···");
                cyclic.await();
                System.out.println(soldier+"集合完比，各自执可以执行了···");
                doWork();
                cyclic.await();

            } catch (Exception e) {

            }

        }

        private void doWork() {
            try {
                System.out.println(soldier+"-开始执行任务");
                Thread.sleep(Math.abs(new Random().nextInt()%10000));
            } catch (Exception e) {

            }
            System.out.println(soldier+"任务完成！");
        }
    }

    public static class BarrideRun implements Runnable {
        boolean flag;
        int N;
        public BarrideRun(boolean flag,int N){
            this.N=N;
            this.flag=flag;
        }
        @Override
        public void run() {
            if (flag) {
                System.out.println("司令:{士兵" + N + "} 个，任务完成！");
            } else {
                System.out.println("司令:{士兵" + N + "} 个，集合完毕！");
                flag=true;
            }

        }
    }

    public static void main(String[] args) {
        final  int a=100;
        Thread[] allSoldier = new Thread[a];
        boolean flag=false;
//      条件达到后会回执行这个任务  完成之后就执行BarrideRun这个方法
        CyclicBarrier cyclic = new CyclicBarrier(a, new BarrideRun(flag, a));
        System.out.println("集合队伍！");
        for (int i = 0; i < a; ++i) {
            System.out.println("士兵["+i+"]报道!");
            allSoldier[i]=new Thread(new Soldier(cyclic,"士兵"+i));
            allSoldier[i].start();
        }
    }


}
